﻿using DryIoc;
using Example;
using HandyControl.Controls;
using log4net;
using log4net.Config;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Client.ViewModels;
using PlaceOrder_Client.Views;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System.Configuration;
using System.Data;
using System.IO;
using System.Reflection;
using System.Windows;
using Application = System.Windows.Application;
using Window = System.Windows.Window;
using DevExpress.Xpf.Core;
using MessageBox = HandyControl.Controls.MessageBox;
using System.Windows.Input;
using PlaceOrder_Client.Helper;
using PlaceOrder_Client.Models.Config;
using System.Globalization;
using HandyControl.Tools;
using PlaceOrder_Client.Events;
using System.Diagnostics;
using OfficeOpenXml;
using Newtonsoft.Json;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using DevExpress.Xpf.Grid;

namespace PlaceOrder_Client
{
   
    public partial class App : PrismApplication
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(App));
        private static Mutex mutex;

        public Stopwatch stopwatch = new Stopwatch();
        private KeyboardHooker _keyboardHooker;
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // Register log4net logger instance
            containerRegistry.RegisterInstance(log);

            // Register other types
            containerRegistry.Register<ILoginService, LoginService>();

            containerRegistry.RegisterSingleton<IUserHelper, UserHelper>();
            containerRegistry.RegisterSingleton<IDataHelper, DataHelper>();
            containerRegistry.RegisterSingleton<IDatabase, Database>();
            containerRegistry.RegisterSingleton<IDailyData, DailyData>();
            containerRegistry.RegisterSingleton<IData, Data>();
       

            containerRegistry.RegisterDialog<LoginView, LoginViewModel>();

            //containerRegistry.RegisterDialog<OrderView, OrderViewModel>();


            //导航
            containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();
            containerRegistry.RegisterForNavigation<OrderListView, OrderListViewModel>();
            containerRegistry.RegisterForNavigation<ChatMessageView, ChatMessageViewModel>();
            containerRegistry.RegisterForNavigation<TransactionReviewView, TransactionReviewViewModel>();
            containerRegistry.RegisterForNavigation<QiangPingCountDownView, QiangPingCountDownViewModel>();
            containerRegistry.RegisterForNavigation<ChatWorkOrderView, ChatWorkOrderViewModel>();
            //containerRegistry.Register<ChatWindowViewModel>();
            containerRegistry.Register<ChatWindow>();
            //单例
            containerRegistry.RegisterSingleton<MainViewModel>();
            containerRegistry.RegisterMany<LongHuViewModel>();
            containerRegistry.RegisterSingleton<OrderListViewModel>();
            containerRegistry.RegisterSingleton<ChatMessageViewModel>();
            containerRegistry.RegisterSingleton<DailyOrderStatusViewModel>();
            containerRegistry.RegisterSingleton<DefaultTradingVolumeViewModel>();
            containerRegistry.RegisterSingleton<TransactionReviewView>();
            containerRegistry.RegisterSingleton<TransactionReviewViewModel>();
            containerRegistry.RegisterSingleton<ChatMessageWindow>();
            containerRegistry.RegisterSingleton<QiangPingWindow>();
            containerRegistry.RegisterSingleton<ChatWorkOrderView>();



            ///多个实例
            containerRegistry.RegisterMany<ChatWindowViewModel>();
        }

        protected override Window CreateShell()
        {
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
            AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
            return ContainerLocator.Container.Resolve<MainView>();
        }
        public  WindowConfig config;
        protected override void OnInitialized()
        {
            SetupDailyStopTimer(); //每日9.50分停止抓取
            stopwatch.Stop();
            AppLog.WriteInfo("App加载时间"+stopwatch.Elapsed.Milliseconds);
            var dialog = ContainerLocator.Container.Resolve<IDialogService>();
            dialog.ShowDialog("LoginView", callback =>
            {
                if (callback.Result != ButtonResult.OK)
                {
                    Environment.Exit(0);
                    return;
                }
                // 加载并应用窗口配置
  
                
                if (App.Current.MainWindow.DataContext is IConfigureService service)
                {
                    service.Configure();
                }
                base.OnInitialized();
            });


        }
        private static System.Timers.Timer stopTimer;
        private void SetupDailyStopTimer()
        {
            // 记录程序启动时间
            DateTime startTime = DateTime.Now;
            DateTime now = DateTime.Now;

            // 计算13.5个小时后的时间点
            DateTime maxRunTime = startTime.AddHours(13.5);

            // 计算早上7点的时间点
            DateTime nextStopTime = DateTime.Today.AddHours(7).AddMinutes(00);

  
            if (now > nextStopTime)
            {
                // 如果当前时间已经过了早上7点，那么设置为明天早上7点
                nextStopTime = nextStopTime.AddDays(1);
            }

            // 计算距离13.5小时的时间间隔
            TimeSpan timeUntilMaxRun = maxRunTime - now;

            // 计算距离早上7点的时间间隔
            TimeSpan timeUntilNextStop = nextStopTime - now;

            // 选择最短的时间间隔作为定时器的触发时间
            TimeSpan timerInterval = timeUntilMaxRun < timeUntilNextStop ? timeUntilMaxRun : timeUntilNextStop;

            stopTimer = new System.Timers.Timer(timerInterval.TotalMilliseconds);
            stopTimer.Elapsed += (o, a) =>
            {
                // 停止主定时器
                AppLog.WriteInfo("程序关闭了！");
                MessageBox.Show("会话已过期，请重新开启软件！","提示",MessageBoxButton.OK);
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    PrismApplication.Current.Shutdown();
                });
            };
            stopTimer.AutoReset = false; // 只执行一次
            stopTimer.Start();
        }


        protected override void OnStartup(StartupEventArgs e)
        {
            // 启用无限高度/宽度
            //GridControl.AllowInfiniteGridSize = true;
            stopwatch.Start();
            //var accentpalette = new Win10Palette();
            //var customtheme = Theme.CreateTheme(accentpalette, Theme.Win10Light);
            //Theme.RegisterTheme(customtheme);
            // Ensure the log directory exists
            _keyboardHooker = new KeyboardHooker();
            _keyboardHooker.ShortcutPressed += HandleGlobalShortcut;
            //_keyboardHook.KeyPressed += KeyboardHook_KeyPressed;
            //string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
            //if (!Directory.Exists(logDirectory))
            //{
            //    Directory.CreateDirectory(logDirectory);
            //}

            // Configure log4net
            log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));

            ExcelPackage.LicenseContext = LicenseContext.Commercial; // 如果你有商业许可证

            //bool isOwned;
            //string mutexName = "Global\\QuanYiPlaceOrderClient";

            //mutex = new Mutex(true, mutexName, out isOwned);

            //if (!isOwned)
            //{
            //    log.Warn("Another instance of the application is already running.");
            //    MessageBox.Show("有另一相同程序正在运行，请检查！");

            //    Thread.Sleep(200);
            //    Application.Current.Shutdown();
            //    return;
            //}
            AppLog.CleanupOldLogs();
            AppLog.WriteInfo("程序启动");
            base.OnStartup(e);
            // 加载并应用窗口配置
            string filePath = MainViewModel.ConfigFilePath;
            if (File.Exists(filePath))
            {
                string json = File.ReadAllText(filePath);
                var config = JsonConvert.DeserializeObject<WindowConfig>(json);

                if (config != null && config.WindowPositions != null)
                {
                    var mainView = config.WindowPositions.ContainsKey("MainView") ? config.WindowPositions["MainView"] : new List<WindowPosition>();

                    if (mainView == null || mainView.Count == 0)
                    {
                        var screenWidth = SystemParameters.PrimaryScreenWidth;
                        var screenHeight = SystemParameters.PrimaryScreenHeight;
                        App.Current.MainWindow.Left = (screenWidth / 2) - (App.Current.MainWindow.Width / 2);
                        App.Current.MainWindow.Top = (screenHeight / 2) - (App.Current.MainWindow.Height / 2);
                    }
                    else
                    {
                        App.Current.MainWindow.Width = mainView[0].Width;
                        App.Current.MainWindow.Height = mainView[0].Height;
                        App.Current.MainWindow.Top = mainView[0].Top;
                        App.Current.MainWindow.Left = mainView[0].Left;
                    }
                }
            }else
            {
                // File does not exist, create a new default configuration file
                var defaultConfig = new WindowConfig
                {
                    WindowPositions = new Dictionary<string, List<WindowPosition>>
                {
                    { "LongHuView", new List<WindowPosition>() },
                    { "MainView", new List<WindowPosition>() },
                    { "OnHoldView", new List<WindowPosition>() },
                    { "ChatMessageView", new List<WindowPosition>() },
                    { "OrderView", new List<WindowPosition>() }
                },
                    BrokerName = new List<string>()
                };

                // Serialize the default configuration to JSON
                string defaultJson = JsonConvert.SerializeObject(defaultConfig, Formatting.Indented);

                // Write the JSON to the file
                File.WriteAllText(filePath, defaultJson);

                // Set default window position
                App.Current.MainWindow.Width = 800;
                App.Current.MainWindow.Height = 600;
                App.Current.MainWindow.Top = (SystemParameters.PrimaryScreenHeight / 2) - (600 / 2);
                App.Current.MainWindow.Left = (SystemParameters.PrimaryScreenWidth / 2) - (800 / 2);
            }

            AppLog.WriteInfo("窗口配置已加载");
            //GlobalHotKey hotKey;
            //hotKey = new GlobalHotKey(Key.F6, ModifierKeys.None, () => BringToFrontWindow());
            //hotKeyManager.RegisterHotKey(Key.F4, ModifierKeys.None, () => BringToFrontWindow()); // F4 对应第二个窗口
            //hotKeyManager.RegisterHotKey(Key.F5, ModifierKeys.None, () => BringToFrontWindow()); // F5 对应第三个窗口
            //hotKeyManager.RegisterHotKey(Key.F6, ModifierKeys.None, () => BringToFrontWindow()); // F6 对应第四个窗口

        }

        private void HandleGlobalShortcut()
        {
            PrismApplication.Current.Dispatcher.Invoke(() =>
            {
                foreach (Window window in Current.Windows)
                {
                    if (window.WindowState == WindowState.Minimized)
                    {
                        window.WindowState = WindowState.Normal;
                    }
                    window.Activate();
                }
            });
            
        }

        private void BringToFrontWindow()
        {
            // 获取所有符合条件的窗口，并按照它们在应用程序中的顺序处理
            var windows = Application.Current.Windows.OfType<OrderView>().ToList();

            // 找到最后一个置顶的窗口
            var lastTopmostWindow = windows.FirstOrDefault(w => w.Topmost);

            // 如果最后一个置顶的窗口不为null，取消其置顶状态
            if (lastTopmostWindow != null)
            {
                lastTopmostWindow.Topmost = false;
            }

            // 标记是否找到了要置顶的窗口
            bool found = false;

            // 遍历所有符合条件的窗口
            foreach (var window in windows)
            {
                // 如果找到了一个窗口需要处理
                if (!found)
                {
                    // 如果窗口当前处于最小化状态，将其恢复为正常状态
                    if (window.WindowState == WindowState.Minimized)
                    {
                        window.WindowState = WindowState.Normal;
                    }

                    // 置顶窗口
                    window.Topmost = true;
                    found = true; // 标记已经处理了置顶
                }
                else
                {
                    // 将其他窗口的置顶状态取消
                    window.Topmost = false;
                }
            }
        }




        protected override void OnExit(ExitEventArgs e)
        {
            log.Info("Application exited");
            //Growl.FatalGlobal("有另一相同程序正在运行，请检查！");
            //MessageBox.Show("有另一程序正在运行，请检查！","提示");
            mutex?.ReleaseMutex();
            base.OnExit(e);
        }
    }
}
